package com.labichaoka.chaoka.net;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.labichaoka.chaoka.entity.ApiException;
import com.labichaoka.chaoka.entity.HttpStatus;

import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;

import static com.labichaoka.chaoka.utils.FileUtil.UTF_8;


/**
 * Created by ruan on 2018/6/4.
 */

public class CustomGsonResponseConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomGsonResponseConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

            String response = value.string();
//            // 解密
//            String body = EncryptUtils.decryptParams(originalBody);
//            // 获取json中的code，对json进行预处理
            HttpStatus httpStatus = gson.fromJson(response, HttpStatus.class);
            if (!httpStatus.isSuccess()){
                value.close();
                throw new ApiException(Integer.parseInt(httpStatus.getCode()),httpStatus.getMessage());
            }

//            JSONObject json = new JSONObject(originalBody);
//            int code = json.optInt("code");
//            if (code==-405){
//                //未登录
////                new SendBroadCastUtil(MyApplication.mContext).sendBroad
////                        (GlobalParams.LOGIN_SUCCESS_ACTION, null);
//            }
//            // 当code不为0时，设置data为{}，这样转化就不会出错了
//            if (code != 0) {
//                json.put("data", new JSONObject());
//                body = json.toString();
//            }

//            return adapter.fromJson(body);
        try {
            return adapter.fromJson(response);
        }  finally {
            value.close();
        }
    }
}
